import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const ctxResponse = ctx.getResponse();
    const ctxRequest = ctx.getRequest();
    const statusCode = exception.getStatus();
    const response = exception.getResponse() as {
      statusCode: number;
      message: any;
      error: string;
    };
    const errors = response.message;

    const message = Array.isArray(errors)
      ? errors.map(err => Object.values(err.constraints)).reduce((acc, val) => acc.concat(val), [])[0]
      : response.message;

    if (statusCode >= 500) {
      console.error(exception);
    } else {
      console.log(response);
    }

    ctxResponse
      .status(statusCode)
      .json(Object.assign({}, {
        code: statusCode,
        path: ctxRequest.path,
        timestamps: Date.now(),
        message
      }))
  }
}